package com.sdp.right.api;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import com.alibaba.fastjson.JSON;
import com.sdp.core.bizc.annotation.ApiSecure;
import com.sdp.core.bizc.exception.ApplicationException;
import com.sdp.core.bizc.vo.Result;

@Aspect
@Component
public class ApiSecureAspect {
	
	@Pointcut("@annotation(com.sdp.core.bizc.annotation.ApiSecure)")
    public void apiSecurePointcut() {}

	@Around("apiSecurePointcut()")
    public Object doSecurityCheck(ProceedingJoinPoint joinPoint) throws Throwable {
		Result<?> r = Result.error();
		
		// 获取RequestAttributes
		RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

		// 从获取RequestAttributes中获取HttpServletRequest的信息
		HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);

		MethodSignature signature = (MethodSignature) joinPoint.getSignature();
		Method method = signature.getMethod();
		ApiSecure apiSecure = method.getAnnotation(ApiSecure.class);
		
		//从header获取key和appId 如果不存在不能调用
		String apiKey = request.getHeader("sdp-api-key");
		String appId = request.getHeader("sdp-api-appId");
		if(StringUtils.isEmpty(apiKey) || StringUtils.isEmpty(appId)) {
			r.setSuccess(false);
			r.setCode("401");
			r.setMessage("请求未授权");
			throw new ApplicationException(JSON.toJSONString(r));
		}
		
		//通过key和appId 查询是否正确
		
		
		//验证频次
		
		
		return joinPoint.proceed();
	}
}
